package com.lagou.edu.ctrl;

import com.lagou.api.CodeServcie;
import com.lagou.api.EmailService;
import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class CodeImpl  implements CodeServcie {

    @Autowired
    AuthCodeDao authCodeDao;

    @Reference
    EmailService  mailServicee;

    @Override
    public boolean create(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }

        int num = ThreadLocalRandom.current().nextInt(100000, 999999);
        //send email
        boolean rst = mailServicee.send(email, num + "");
        if (rst) {

            //clear old
            authCodeDao.delete(new AuthCode().setEmail(email));
            //save code
            authCodeDao.save(new AuthCode().setCode(num + "").setEmail(email).setCreateTime(new Date())
                    .setExpireTime(new Date(System.currentTimeMillis()+10*60*1000)));



        }

        return rst;
    }

    @Override
    public boolean validate(String email, String code) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        if (StringUtils.isEmpty(code)) {
            return false;
        }

        // check code
        return authCodeDao.count(Example.of(new AuthCode().setEmail(email).setCode(code))) > 0;
    }
}
